# -*- coding: UTF-8 -*-
from . import db
import json
from sqlalchemy import distinct

#server 表的对象
class Server(db.Model):
    __tablename__ = 'server'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    server_ip = db.Column(db.String(512), unique=True)
    server_group = db.Column(db.String(512))


def server_query_id_server_group():
    return db.session.query(distinct(Server.server_group)).all()

#server对象添加
def server_add(server_obj):
    db.session.add(server_obj)
    db.session.commit()

def server_update(id, server_ip, server_group):
    soft_obj = Server.query.filter_by(id=id).first()
    soft_obj.server_ip = server_ip
    soft_obj.server_group = server_group
    db.session.commit()

def server_delete_from_id(id):
    obj = Server.query.filter_by(id = id).first()
    db.session.delete(obj)
    db.session.commit()

def server_query_all():
    result = []
    server_objs = Server.query.all()
    for server_obj in server_objs:
        tmp = {}
        tmp['id'] = server_obj.id
        tmp['server_ip'] = server_obj.server_ip
        tmp['server_group'] = server_obj.server_group
        result.append(tmp)
    return json.dumps(result)